package com.qfedu.edu.iotserver.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qfedu.edu.exception.handler.BusinessException;
import com.qfedu.edu.iotserver.mapper.DeviceMapper;
import com.qfedu.edu.iotserver.mapper.OrderDetailMapper;
import com.qfedu.edu.iotserver.mapper.OrderMapper;
import com.qfedu.edu.iotserver.service.OrderService;
import com.qfedu.edu.iotserver.utils.OrderNumberUtils;
import com.qfedu.edu.pojo.Device;
import com.qfedu.edu.pojo.Order;
import com.qfedu.edu.pojo.OrderDetail;
import com.qfedu.edu.result.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(Order order) {
        //参数检测
        parameterCheck(order);
        //订单插入
        insertOrder(order);
        //订单详情插入
        insertOrderDetail(order);
    }

    @Override
    public void updateOrderStatus(String orderNumber, Integer status) {
        if(StringUtils.isEmpty(orderNumber)||null==status){
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION.getCode(),ResponseCode.PARAMETER_EXCEPTION.getMsg());
        }
        //首先通过订单号查询
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("order_num",orderNumber);
        Order order = orderMapper.selectOne(orderQueryWrapper);
        if(null==order){
            //说明订单号不对
            throw new BusinessException(ResponseCode.ORDER_NUMBER_EXCEPTION.getCode(),ResponseCode.ORDER_NUMBER_EXCEPTION.getMsg());
        }
        //执行到这里 说明查询到了
        order.setStatus(status);
        orderMapper.updateById(order);
    }

    @Override
    public Integer getOrderStatus(String orderNumber) {
        if(StringUtils.isEmpty(orderNumber)){
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION.getCode(),
                    ResponseCode.PARAMETER_EXCEPTION.getMsg());
        }
        //执行到这里说明没有问题
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("order_num",orderNumber);
        Order order = orderMapper.selectOne(orderQueryWrapper);
        if(null!=order){
           return order.getStatus();
        }
        //如果执行到这里
        throw new BusinessException(ResponseCode.ORDER_NUMBER_EXCEPTION.getCode()
                ,ResponseCode.ORDER_NUMBER_EXCEPTION.getMsg());
    }

    /**
     * 向订单详情表插入数据
     * @param order
     */
    public void insertOrderDetail(Order order) {
        //接下来通过产品id查询设备信息
        QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
        deviceQueryWrapper.eq("product_id", order.getProductId());
        //查询设备信息
        List<Device> devices = deviceMapper.selectList(deviceQueryWrapper);
        if(null==devices){
             throw new BusinessException(ResponseCode.PRODUCT_ID_EXCEPTION.getCode(),
                     ResponseCode.PRODUCT_ID_EXCEPTION.getMsg());
        }
        //执行到这里说明不为空
        for (int i = 0; i < devices.size(); i++) {
            //取出这个设备信息
            Device device = devices.get(i);
            //接下来构建咋们的OrderDetail对象
            OrderDetail orderDetail=new OrderDetail();
            orderDetail.setOrderId(order.getOrderId());
            orderDetail.setDeviceId(device.getId());
            orderDetail.setDeviceName(device.getName());
            orderDetail.setDeviceSinglePrice(device.getPrice());
            orderDetail.setDeviceCount(device.getCount());
            //接下来计算这个总价
            //总价=数量*单价
            Integer count = device.getCount();
            BigDecimal price = device.getPrice();
            BigDecimal totalPrice = new BigDecimal(count).multiply(price);
            orderDetail.setDeviceAllPrice(totalPrice);
            //接下来插入数据到 数据库
            orderDetailMapper.insert(orderDetail);
        }
    }

    public void insertOrder(Order order) {
        //执行到这里说明参数无误
        //那么就设置参数
        //订单号的生成(订单号在你的这个系统中必须是唯一的)
        order.setOrderNum(OrderNumberUtils.getOrderNumber());
        //设置未支付的状态
        order.setStatus(0);
        //于是将订单信息插入到订单表中
        orderMapper.insert(order);
    }

    /**
     * 参数校验
     * @param order
     */
    private static void parameterCheck(Order order) {
        //首先校验的是参数的合法性
        if(null== order ||null== order.getPayMoney()||null== order.getPayType()|| StringUtils.isEmpty(order.getTenantId())||StringUtils.isEmpty(order.getProductName())||StringUtils.isEmpty(order.getProductId())){
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION.getCode(),
                    ResponseCode.PARAMETER_EXCEPTION.getMsg());
        }
    }
}
